/*
 * @Author: zhangyun
 * @Date: 2021-04-26 09:20:09
 * @LastEditors: zhangyun
 * @LastEditTime: 2021-04-26 15:30:14
 * @Desc:
 */
const express = require('express')
const router = express.Router()
const _ = require('lodash')
const userModel = require('../model/userModel')
const message = require('../utils/message')

router.get('/', (req, res) => {
  const { id } = req.query
  if (id) {
    userModel
      .findById(id)
      .then((result) => {
        res.status(200).send(message(200, '查询成功', result))
      })
      .catch((err) => {
        res.status(400).send(message(400, '查询失败'))
      })
  } else {
    userModel
      .find()
      .then((result) => {
        res.status(200).send(message(200, '查询成功', result))
      })
      .catch((err) => {
        res.status(400).send(message(400, '查询失败'))
      })
  }
})

router.delete('/', (req, res) => {
  const { id } = req.query
  if (_.isEmpty(id)) return res.status(400).send(message(400, 'id不能为空'))
  userModel
    .findById(id)
    .deleteOne()
    .then(() => {
      res.status(200).send(message(200, '用户删除成功'))
    })
    .catch((err) => {
      console.log(err)
      res.status(400).send(message(400, '用户删除失败'))
    })
})

router.post('/', (req, res) => {
  const { user, pwd, sex } = req.body
  if (_.isEmpty(user)) return res.status(400).send(message(400, '用户名称不能为空'))
  if (_.isEmpty(pwd)) return res.status(400).send(message(400, '用户密码不能为空'))
  const userForm = {
    user: user,
    pwd: pwd,
    sex: sex || 'man',
  }
  userModel
    .find({ user })
    .then((data) => {
      if (data.length === 0) {
        return userModel.insertMany(userForm)
      } else {
        res.status(400).send(message(400, '用户已存在'))
      }
    })
    .then(() => {
      res.status(200).send(message(200, '用户创建成功'))
    })
    .catch((err) => {
      res.status(400).send(message(400, '用户创建失败'))
    })
})

module.exports = router
